﻿using Avalonia.Controls.Notifications;
using Digitalmes.Core.Services;

namespace Digitalmes.AvaloniaUI.ViewModels;

/// <summary>
/// 系统配置
/// </summary>
public sealed partial class SettingsViewModel : ViewModelBase
{
    private WindowToastManager? _toastManager;

    private readonly IParamStandardService _paramStandardService;
    private readonly ICounterService _counterService;

    [NotNull]
    public ObservableCollection<StandardParam>? Standards { get; set; }

    [ObservableProperty]
    public partial int CounterNumber { get; set; } = 0;

    [RelayCommand]
    public async Task ChangeStandard(string paramCode)
    {
        var param = Standards.First(s => s.ParamCode == paramCode);
        await _paramStandardService.ChangeStandardAsync(paramCode, param.MinLimit, param.MaxLimit, param.IsEnabled);
        ShowToast("修改成功");
    }

    [RelayCommand]
    public async Task ResetCounter()
    {
        await _counterService.ResetAsync("number_rotations");
        CounterNumber = 0;
    }

    public SettingsViewModel(IParamStandardService paramStandardService, ICounterService counterService)
    {
        _paramStandardService = paramStandardService;
        _counterService = counterService;

        var standards = _paramStandardService.GetStandardListAsync().Result;
        Standards = new(standards.Select(m => new StandardParam
        {
            ParamCode = m.ParamCode,
            ParamName = m.ParamName,
            MinLimit = m.MinLimit,
            MaxLimit = m.MaxLimit,
            IsEnabled = m.IsEnabled,
        }));
        CounterNumber = _counterService.GetCurrentAsync("number_rotations").Result;
    }

    private void ShowToast(string message)
    {
        _toastManager ??= new(TopLevel) { MaxItems = 3 };
        _toastManager.Show(
                new Toast(message),
                showIcon: false,
                showClose: false,
                type: NotificationType.Success,
                expiration: TimeSpan.FromSeconds(3),
                classes: ["Light"]);
    }

    public class StandardParam : ObservableObject
    {
        public string? ParamCode { get; set; }

        public string? ParamName { get; set; }

        public double MinLimit { get; set; }

        public double MaxLimit { get; set; }

        public bool IsEnabled { get; set; }
    }
}
